package com.glorysoft.lipuxinpda.activity;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.glorysoft.lipuxinpda.R;
import com.glorysoft.lipuxinpda.adapter.RecyclerViewAdapter;
import com.glorysoft.lipuxinpda.base.BaseActivity;
import com.glorysoft.lipuxinpda.base.Constant;
import com.glorysoft.lipuxinpda.entity.BasShortcutIconInfoEntity;
import com.glorysoft.lipuxinpda.entity.BaseEntity;
import com.glorysoft.lipuxinpda.entity.EqpInfoEntity;
import com.glorysoft.lipuxinpda.entity.LoginEntity;
import com.glorysoft.lipuxinpda.entity.PDALoginReturnEntity;
import com.glorysoft.lipuxinpda.recyevent.OnRecyclerItemClickListener;
import com.glorysoft.lipuxinpda.recyevent.RecyItemTouchHelperCallback;
import com.glorysoft.lipuxinpda.utils.AppUntils;
import com.glorysoft.lipuxinpda.utils.FileUtils;
import com.glorysoft.lipuxinpda.utils.GsonUtils;
import com.glorysoft.lipuxinpda.utils.NetUtils;
import com.glorysoft.lipuxinpda.utils.ResultSet;
import com.glorysoft.lipuxinpda.utils.SharedPreferencesUtil;
import com.glorysoft.lipuxinpda.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class HomeActivity extends BaseActivity {
    private final String TAG = HomeActivity.class.getSimpleName();
    private Context mContext;

    private ViewPager mViewPager;
    private View viewFunction; //功能管理
    private View viewInfoCheck; //信息查询
    private View viewMineInfo; //我的信息

    private RadioGroup rg_bottom_radio_group;
    private RadioButton rb_bottom_function; //功能管理
    private RadioButton rb_bottom_info_check; //信息查询
    private RadioButton rb_bottom_mine_info; //我的信息
    private RecyclerView recyclerView; //显示-快捷图标


    //我的信息
    private TextView tv_name;//姓名
    private TextView tv_work_no;//工号
    private TextView tv_phone_num;//手机号
    private TextView tv_email;//邮箱
    private TextView tv_position;//职位
    private TextView tv_class;//班别


    private List<View> viewList = new ArrayList<View>(); //滑动UI
    private FunPagerAdapter mAdapter; //首页菜单-适配器

    //快捷方式数据
    private List<BasShortcutIconInfoEntity> mBasShortcutIconInfoList = null;
    private RecyclerViewAdapter mRecyclerViewAdapter; //快捷方式适配器


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListenerView();//控件事件

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        mContext = this;

        mViewPager = findViewById(R.id.view_pager);
        //功能管理
        viewFunction = View.inflate(mContext, R.layout.fragment_main_bottom_function, null);
        //信息查询
        viewInfoCheck = View.inflate(mContext, R.layout.fragment_main_bottom_info_check, null);
        //我的信息
        viewMineInfo = View.inflate(mContext, R.layout.fragment_main_bottom_mine_info, null);

        //单选组、按钮
        rg_bottom_radio_group = findViewById(R.id.rg_bottom_radio_group);
        rb_bottom_function = findViewById(R.id.rb_bottom_function);
//        rb_bottom_info_check = findViewById(R.id.rb_bottom_info_check);
        rb_bottom_mine_info = findViewById(R.id.rb_bottom_mine_info);

        //viewList添加数据
        viewList.add(viewFunction);
//        viewList.add(viewInfoCheck);
        viewList.add(viewMineInfo);
    }

    @Override
    protected void initData() {

        //首页底部菜单-适配器
        mAdapter = new FunPagerAdapter(viewList);
        mViewPager.setAdapter(mAdapter);

        //修改RadioButton drawableTop图片大小 --图片放在drawable-xxhdpi目录下，此处则不用修改
//        modifyRadioButton();

        //初始化数据-功能管理
        initFragmentMmainFunctionView();
        //初始化数据-信息查询
        initFragmentMmainCheckInfoView();
        //初始化数据-我的的信息
        initFragmentMmainMineInfoView();

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    //region 首页底部菜单页面滑动-初始化数据

    //初始化数据-首页
    private void initFragmentMmainFunctionView() {
        recyclerView = viewFunction.findViewById(R.id.rv_recycler_view);  //显示-快捷图标

        if (mBasShortcutIconInfoList == null) {
            mBasShortcutIconInfoList = new ArrayList<>();
        }

        //region 获取本地Json数据(快捷图标)

        try {
            //获取本地Json数据(快捷图标)
            ResultSet resultSetData = FileUtils.readJson(mContext, "shortcut_json.txt");
            if (resultSetData.status == 0) {
                String sShortcutJson = resultSetData.getData().toString();
                if (!TextUtils.isEmpty(sShortcutJson)) {
                    //解析JSON
                    JSONArray jsonArray = new JSONArray(sShortcutJson);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String sData = jsonObject.getString("data");
                    JSONArray jsonArrayData = new JSONArray(sData);
                    JSONObject jsonObjectData = jsonArrayData.getJSONObject(0);
                    PDALoginReturnEntity mPDALoginReturnEntity = GsonUtils.getObject(jsonObjectData.toString(), PDALoginReturnEntity.class);
                    List<BasShortcutIconInfoEntity> authArray = new ArrayList<BasShortcutIconInfoEntity>();
                    /*页面展示内容权限校验,根据后台的传值,具体展示快捷图标，切换用户和退出快捷图标一直显示*/
                    if(Constant.INSTANCE.getLoginEntity().getAUTHORITYLIST() == null ||  Constant.INSTANCE.getLoginEntity().getAUTHORITYLIST() == ""){
                        for (BasShortcutIconInfoEntity basShortcutIconInfoEntity:mPDALoginReturnEntity.getTabIndexGridEntityList()) {
                                 if(basShortcutIconInfoEntity.getText().equals("退出") || basShortcutIconInfoEntity.getText().equals("切换用户")){
                                     authArray.add(basShortcutIconInfoEntity);
                                 }
                        }
                    }else{
                        String[] arraylist = (Constant.INSTANCE.getLoginEntity().getAUTHORITYLIST() + "F6;F7;").split(";");
                        List<String> list = new ArrayList<String>();
                        list = Arrays.asList(arraylist);
                        for (String auth:list) {
                            String authname = AppUntils.getTypeZH(auth);
                            for (BasShortcutIconInfoEntity basShortcutIconInfoEntity:mPDALoginReturnEntity.getTabIndexGridEntityList()) {
                                if(basShortcutIconInfoEntity.getText().equals(authname)){
                                    authArray.add(basShortcutIconInfoEntity);
                                }
                            }
                        }
                    }
                    mBasShortcutIconInfoList.addAll(authArray);
                } else {
                    ToastUtil.showShortToast(mContext, resultSetData.msg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


//endregion


//region 初始化数据

        if (mBasShortcutIconInfoList.size() >= 1) {

            //设置网格布局管理器
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            // 设置adapter
            mRecyclerViewAdapter = new RecyclerViewAdapter(mContext, R.layout.item_main_operate, mBasShortcutIconInfoList);

            //分割线
            //recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
            recyclerView.setHasFixedSize(true);

            // recyclerView  调用自己的addOnItemTouchListener方法，参数传入我们定义的类RecyclerItemClickListener的实例
            recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView) {
                /**
                 * 点击事件
                 *
                 * @param viewHolder
                 */
                @Override
                public void onItemClick(RecyclerView.ViewHolder viewHolder, String sTag) {
                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    String sShortcutTag = sTag;
                    Log.e(TAG, "点击了快捷方式图标：" + sShortcutName);
                    //首页-快捷方式
                    openShortcutActivity(sShortcutTag);
                }

                /**
                 * 长按事件
                 *
                 * @param viewHolder
                 */

                @Override
                public void onLongClick(RecyclerView.ViewHolder viewHolder, String sTag) {

                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    Log.e(TAG, "长按了快捷方式图标：" + sShortcutName);
                }
            });

            recyclerView.setAdapter(mRecyclerViewAdapter);

        }

        //endregion
    }

    //初始化数据-信息查询
    private void initFragmentMmainCheckInfoView() {
    }

    //初始化数据-任务
    private void initFragmentMmainMineInfoView() {
        tv_name = viewMineInfo.findViewById(R.id.tv_name);
        tv_class = viewMineInfo.findViewById(R.id.tv_class);
        tv_phone_num = viewMineInfo.findViewById(R.id.tv_phone_num);
        tv_position = viewMineInfo.findViewById(R.id.tv_position);
        tv_work_no = viewMineInfo.findViewById(R.id.tv_work_no);
        tv_email = viewMineInfo.findViewById(R.id.tv_email);

        searchUserInfo();//查询个人信息

        //region 测试

//       String sJson = "{" +
//                "     \"data\":{\n" +
//                "       \"WORK_NO\":\"I6229\",\n" +
//                "       \"NAME\":\"童万琴\",\n" +
//                "       \"SHIFT\":\"B\",\n" +
//                "       \"MOBILE_PHONE\":\"\",\n" +
//                "       \"EMAIL\":\"\"\n" +
//                "    }\n" +
//                "    }";
//
//       try {
//           String data = new JSONObject(sJson).getString("data");
//           LoginEntity entity = GsonUtils.getObject(data, LoginEntity.class);
//           showMineInfo(entity);//显示个人信息
//       }catch (JSONException e){
//           e.printStackTrace();
//       }

    }


//endregion


    //region 首页-快捷方式、功能 点击跳转

    //首页-快捷方式
    private void openShortcutActivity(String sShortcutTag) {

        Intent intent = new Intent(mContext, DialogActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        switch (sShortcutTag) {

            //批次开始操作
            case "BatchWorkBeginActivity":

                //region 批次开始操作
                intent.putExtra("showPlugin", "BatchWorkBeginActivity");
                break;

            //endregion

            //批次结束操作
            case "BatchWorkEndActivity":

                //region 批次结束操作
                intent.putExtra("showPlugin", "BatchWorkEndActivity");

                break;

            //endregion

            //切换用户
            case "SwitchingUsers":

                //region 切换用户
                intent.putExtra("showPlugin", "SwitchingUsers");
                break;

            //endregion

            //退出
            case "Exit":

                //region 退出
                intent.putExtra("showPlugin", "Exit");

                break;

            //endregion

            //材料更换
            case "MaterialExchangeActivity":

                //region 材料更换
                intent.putExtra("showPlugin", "MaterialExchangeActivity");

                break;

            //endregion

            //日检
            case "DaycheckActivity":

                //region 日检
                intent.putExtra("showPlugin", "DaycheckActivity");

                break;

            //endregion

            //解锁
            case "UnlockActivity":

                //region 解锁
                intent.putExtra("showPlugin", "UnlockActivity");

                break;

            //endregion

            //工程模式
            case "EngineerModelActivity":
                //region 解锁

                intent.putExtra("showPlugin", "EngineerModelActivity");
                //endregion
                break;

            //实时消息
            case "RealTimeActivity":
                //region 解锁

                intent.putExtra("showPlugin", "RealTimeActivity");
                //endregion
                break;

        }
        startActivity(intent);

    }

//endregion

    //region 页面滑动-控件事件、切换功能、适配器

    //页面滑动-控件事件
    private void setListenerView() {
        //页面滑动-切换功能
        mViewPager.addOnPageChangeListener(mPageChangeListener);

        //点击-切换功能
        rg_bottom_radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < group.getChildCount(); i++) {
                    if (group.getChildAt(i).getId() == checkedId) {
                        mViewPager.setCurrentItem(i);
                        return;
                    }
                }
            }
        });
    }

    //页面滑动-切换功能
    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {

        /**
         * 当页面在滑动的时候会调用此方法，在滑动被停止之前，此方法回一直得到调用
         *
         * @param position 当前页面，及你点击滑动的页面
         * @param positionOffset 当前页面偏移的百分比
         * @param positionOffsetPixels 当前页面偏移的像素位置
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        /**此方法是页面跳转完后得到调用
         *
         * @param position 当前选中的页面的Position（位置编号）
         */
        @Override
        public void onPageSelected(int position) {
            RadioButton radioButton = (RadioButton) rg_bottom_radio_group.getChildAt(position);
            radioButton.setChecked(true);
        }

        /**
         * 此方法是在状态改变的时候调用
         *
         * @param state 此参数有三种状态（0，1，2）：state ==1的时辰默示正在滑动，state==2的时辰默示滑动完毕了，state==0的时辰默示什么都没做
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    //首页底部菜单-适配器
    private class FunPagerAdapter extends PagerAdapter {

        private List<View> mList;

        public FunPagerAdapter(List mList) {
            this.mList = mList;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView(mList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((ViewPager) container).addView(mList.get(position));
            return mList.get(position);
        }
    }

//endregion

    //region 接口调用

    //查询个人信息
    private void searchUserInfo() {
        FreeUI_EntityCallBack<BaseEntity<LoginEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<LoginEntity>>(new TypeToken<BaseEntity<LoginEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity<LoginEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    String authoritylist = Constant.INSTANCE.getLoginEntity().getAUTHORITYLIST();
                    Constant.INSTANCE.setLoginEntity( response.body().getData().getBody());
                    Constant.INSTANCE.getLoginEntity().setAUTHORITYLIST(authoritylist);
                    showMineInfo(response.body().getData().getBody());//显示个人信息
                }
            }

            @Override
            public void onError(Response<BaseEntity<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "SearchUserInfo");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("WORK_NO", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        String method = Constant.INSTANCE.getNET_URL() + "/SearchUserInfoRequest";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    private void showMineInfo(LoginEntity body) {
        tv_work_no.setText(body.getWORK_NO());
        tv_position.setText(body.getWORK_JOB());
        tv_phone_num.setText(body.getMOBILE_PHONE());
        tv_class.setText(body.getSHIFT());
        tv_name.setText(body.getNAME());
        tv_email.setText(body.getEMAIL());
    }

    //endregion
}